module.exports = class ZSocket {
    constructor() {
        this.chatList = [];
        this.userList = [];
    };
    // 用户操作模块
    login(user, ws) {
        console.log("这是数组：",this.userList);
        const findind = this.userList.findIndex(item => {
            return item.userInfo.name = user;
        });
        if (findind < 0) {
            // 注册
            this.userList.push({
                userInfo: {
                    name: user
                },
                isLive: true,
                wss: ws,
            });
            return;
        }
        // 重连 /登录
        this.userList[findind].isLive = true;
    };
    // 用户离线
    offline(user) {
        this.userList.forEach(item => {
            if (item.userInfo.name == user) {
                item.isLive = false;
                return;
            }
        });
    };
    // 获取用户列表
    get_user_list() {
        let list = [];
        this.userList.map(item => {
            let user = { ...item };
            user.wss = null;
            list.push(user);
        });
        return list;
    }
    // ======================
    // 消息操作模块msgMethords
    // ======================


    // type  1 单发   2群发   3 广播
    sendMsg(data) {
        let { type, recipient, msg } = data;
        switch (type) {
            case 1:
                this.userList.forEach(item => {
                    if (item.userInfo.name == recipient) {
                        item.wss.on('open', function open(req) {
                            console.log('connected');
                        });
                        item.wss.on('close', function close() {
                            console.log('disconnected');
                            item.isLive = false;
                        });

                        this.chatList.push(data);
                        if (item.isLive) {
                            item.wss.send(JSON.stringify(chatList));
                        }
                    }
                });
                break;
            case 2:
                this.userList.forEach(item => {
                    item.wss.send(JSON.stringify(chatList));
                });
                break;
        }
    }
}